package com.ruoyi.crop.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.crop.api.domain.Check;
import com.ruoyi.crop.api.domain.Crop;
import com.ruoyi.crop.api.domain.Warehouse;
import com.ruoyi.crop.domain.CheckVo;
import com.ruoyi.crop.domain.UserWarehouse;
import com.ruoyi.crop.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 农作物Controller
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@RestController
@RequestMapping("crop")
public class CropController extends BaseController {
    @Autowired
    private CropService cropService;
    @Autowired
    private GrowService growService;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private CheckService checkService;
    @Autowired
    private UserWarehouseService userWarehouseService;
    /**
     * 获取农作物列表
     */
    @RequiresPermissions("crop:products:list")
    @GetMapping("/list")
    public TableDataInfo list(Crop crop)
    {
        startPage();
        List<Crop> list = cropService.selectCropList(crop);
        return getDataTable(list);
    }

    @GetMapping("/FeignList")
    public AjaxResult FeignList()
    {
        System.err.println("feign调用");
        List<Crop> list = cropService.listByTypeId();
        return success(list);
    }

    @GetMapping("FeignWarehouseById")
    public AjaxResult FeignWarehouseById(Long userId,Long[] warehouseIds){
        ArrayList<UserWarehouse> list = new ArrayList<>();
        for (int i = 0; i < warehouseIds.length; i++) {
            UserWarehouse userWarehouse = new UserWarehouse();
            userWarehouse.setUserId(Integer.valueOf(userId.toString()));
            userWarehouse.setWarehouseId(Integer.valueOf(warehouseIds[i].toString()));
            list.add(userWarehouse);
        }
        userWarehouseService.saveOrUpdateBatch(list);
        return success();
    }
    @RequestMapping("selectWarehouseListByUserId")
    public List<Long> FeignWarehouseById(Long userId){
        List<Long> warehouses = userWarehouseService.selectRoleListByUserId(userId);
        return warehouses;
    }


    /**
     * 获取农作物添加
     */
    @RequiresPermissions("crop:products:add")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Crop crop)
    {
        long l = System.currentTimeMillis();
        crop.setCropCode("NZW"+l);
        Long userId = SecurityUtils.getUserId();
        crop.setUserId(Math.toIntExact(userId));
        crop.setCreateBy(SecurityUtils.getUsername());
        crop.setCreateTime(new Date());
        return success(cropService.save(crop));
    }
    /**
     * 获取农作物添加
     */
    @RequiresPermissions("crop:products:add")
    @PostMapping("/addYunShu")
    public AjaxResult addYunShu(@RequestBody CheckVo checkVo)
    {
        System.err.println(JSONUtil.toJsonStr(checkVo));
        Check check = new Check();
        long l = System.currentTimeMillis();
        check.setZjId(checkVo.getZjId());
        check.setCheckCode("ZJ"+l);
        check.setTestItemType("检测中");
        check.setMaterialLotId(checkVo.getMaterialLotId());
        check.setProductName(checkVo.getName());
        check.setWarehouseId(checkVo.getWarehouseId());
        check.setDriverId(checkVo.getDriverId());
        check.setCreateBy(SecurityUtils.getUsername());
        check.setCreateTime(new Date());
        check.setRemark("检测");
        check.setMu(checkVo.getMu());
        check.setAxe(checkVo.getAxe());
        check.setCount(checkVo.getHarvest());
        Check one = checkService.getOne(Wrappers.lambdaQuery(Check.class).eq(Check::getMaterialLotId, checkVo.getMaterialLotId()));
        if(one!=null){
            return error("此数据已经被运输");
        }
        checkService.save(check);
        return success();
    }

    /**
     * 查询农作物详细
     */
    @RequiresPermissions("crop:products:query")
    @GetMapping(value = "/{cropId}")
    public AjaxResult getInfo(@PathVariable String cropId)
    {
        return success(cropService.getById(cropId));
    }

    /**
     * 修改农作物
     */
    @RequiresPermissions("crop:products:edit")
    @PutMapping
    public AjaxResult edit(@RequestBody Crop crop)
    {
        crop.setUpdateBy(SecurityUtils.getUsername());
        crop.setUpdateTime(new Date());
        return toAjax(cropService.updateById(crop));
    }


    @PutMapping("UpdateYF/{num}/{cropCode}")
    public AjaxResult UpdateYF(@PathVariable String num,@PathVariable String cropCode)
    {
        System.err.println(num);
        cropService.update(Wrappers.lambdaUpdate(Crop.class).set(Crop::getStatus,1).set(Crop::getHarvest,num).eq(Crop::getCropCode,cropCode));
        return success();
    }

    /**
     * 删除农作物
     */
    @RequiresPermissions("crop:products:remove")
    @DeleteMapping("/{cropIds}")
    public AjaxResult remove(@PathVariable String[] cropIds)
    {
        return toAjax(cropService.removeBatchByIds(Arrays.asList(cropIds)));
    }


    @GetMapping("getZZtime")
    public AjaxResult getZZtime(@RequestParam(value = "zzTime") String zzTime,
                                @RequestParam(value = "seedlingCycle") String seedlingCycle,
                                @RequestParam(value = "irrigationCycle") String irrigationCycle,
                                @RequestParam(value = "fertilizationCycle") String fertilizationCycle,
                                @RequestParam(value = "weedingCycle") String weedingCycle
                                ) throws ParseException {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse(zzTime);
        System.err.println(seedlingCycle);
        System.err.println(irrigationCycle);
        System.err.println(fertilizationCycle);
        System.err.println(weedingCycle);
        BigDecimal bigDecimal1 = new BigDecimal(seedlingCycle);
        BigDecimal bigDecimal2 = new BigDecimal(irrigationCycle);
        BigDecimal bigDecimal3 = new BigDecimal(fertilizationCycle);
        BigDecimal bigDecimal4 = new BigDecimal(weedingCycle);
        String format = "";
        if(seedlingCycle.equals("1")){
            BigDecimal add1 = bigDecimal1.add(bigDecimal1.multiply(new BigDecimal(7)));
            BigDecimal add2 = add1.add(bigDecimal2.multiply(new BigDecimal(7)));
            BigDecimal add3 = add2.add(bigDecimal3.multiply(new BigDecimal(7)));
            BigDecimal add4 = add3.add(bigDecimal4.multiply(new BigDecimal(7)));
            Date date = DateUtil.offsetDay(parse,add4.intValue());
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
            format = simpleDateFormat1.format(date);
            System.err.println(format);
        }
        if(seedlingCycle.equals("2")){
            BigDecimal add1 = bigDecimal1.add(bigDecimal1.multiply(new BigDecimal(14)));
            BigDecimal add2 = add1.add(bigDecimal2.multiply(new BigDecimal(14)));
            BigDecimal add3 = add2.add(bigDecimal3.multiply(new BigDecimal(14)));
            BigDecimal add4 = add3.add(bigDecimal4.multiply(new BigDecimal(14)));
            Date date = DateUtil.offsetDay(parse,add4.intValue());
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
            format = simpleDateFormat1.format(date);
            System.err.println(format);
        }
        return AjaxResult.success(format);
    }

    @GetMapping("getCount")
    public AjaxResult getCount(@RequestParam(value = "mu",required = false) String mu,
                                @RequestParam(value = "axe",required = false) String axe
                                ){
        BigDecimal multiply = new BigDecimal(0);
        if(mu!=null){
            BigDecimal bigDecimal1 = new BigDecimal(mu);
            multiply = bigDecimal1;
            System.err.println(multiply);
        }
        if(axe!=null){
            BigDecimal bigDecimal1 = new BigDecimal(mu);
            BigDecimal bigDecimal2 = new BigDecimal(axe);
            multiply = bigDecimal1.multiply(bigDecimal2);
            System.err.println(multiply);
        }
        return AjaxResult.success(multiply);
    }


    @GetMapping("/getWarehouseList")
    public List<Warehouse> getWarehouseList(){
        List<Warehouse> list = warehouseService.list();
        return list;
    }
    @GetMapping("/selectWarehouseList")
    public AjaxResult selectWarehouseList(){
        List<Warehouse> list = warehouseService.list();
        return success(list);
    }

    @GetMapping("/getWarehouseList2")
    public TableDataInfo getWarehouseList2(Warehouse warehouse){
        startPage();
        List<Warehouse> list = warehouseService.list();
        return getDataTable(list);
    }

}
